package com.example.xyxwebbackend001.service.impl;

import com.example.xyxwebbackend001.service.EmailService;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;


@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public String generateRandomCode() {
        return String.valueOf((int)(Math.random() * 900000 + 100000));
    }

    @Override
    public void sendVerificationCode(String toEmail) {
        try {
            redisTemplate.getConnectionFactory().getConnection().ping();
        } catch (Exception e) {
            return;
        }

        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setFrom("13710140789@163.com");
            helper.setTo(toEmail);
            helper.setSubject("验证码邮件");

            // 添加验证码生成和邮件内容逻辑
            String code = generateRandomCode();
            String key = "email_code:" + toEmail;
            redisTemplate.opsForValue().set(key, code, 1, TimeUnit.MINUTES);
            String storedCode = redisTemplate.opsForValue().get(key);


            message.setText(
                    "【验证密码】验证码为：" + code + "\n"
                    + "有效时间1分钟，请及时完成验证。\n\n"
                    + "安全提示：\n"
                    + "1. 请勿将验证码告知他人\n"
                    + "2. 如非本人操作，请忽略本邮件\n"
                    + "3. 该验证码仅限本次使用\n\n"
                    + "系统自动发送，请勿直接回复 【乡韵墟】");

            mailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException("邮件发送失败", e);
        }
    }

    @Override
    public boolean validateCode(String email, String code) {
        String key = "email_code:" + email;
        String storedCode = redisTemplate.opsForValue().get(key);
        return code != null && code.equals(storedCode);
    }
}
